<template>
  <div class="coupon">
    <h2>优惠卷管理</h2>
    <div class="line-container">
      <div class="box">
        <el-input class="el-input" v-model="searchQuery" placeholder="输入优惠卷名称搜索" @keyup.enter="searchUsers"></el-input>
        <el-button class="el-button" @click="searchUsers">
          <img src="../../assets/img/search.png" alt="">
          筛选
        </el-button>
        <el-button @click="showAddDialog" class="el-button process">
          新增优惠卷
        </el-button>
        <el-button class="el-button remove" @click="deleteSelected" :disabled="selectedUsers.length === 0">
          删除
        </el-button>
      </div>
      <el-table :data="currentCoupons" stripe ref="couponTable" @selection-change="handleTableSelectionChange"
        style="width: 100%;">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="优惠卷信息" width="180">
          <template slot-scope="scope">
            <div>
              <p>{{ scope.row.CouponName }}</p>
              <p>{{ scope.row.CouponId }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="CouponKind" label="类型"></el-table-column>
        <el-table-column prop="CouponMoney" label="优惠金额"></el-table-column>
        <el-table-column prop="CouponKey" label="使用门槛"></el-table-column>
        <el-table-column label="有效期" width="300">
          <template slot-scope="scope">
            <div>
              <span style="margin-right: 10px;">{{ formatTime(scope.row.CouponStarttime) }}</span>至<span
                style="margin-left: 10px;">{{ formatTime(scope.row.CouponEndtime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发放/领取/使用" width="150">
          <template slot-scope="scope">
            <div>
              <span>{{ scope.row.CouponTotal }}</span> / <span>{{ scope.row.CouponRec }}</span> / <span>{{
                scope.row.CouponSit }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="活动状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.couponState" active-color="#13ce66" inactive-color="#ff4949"
              :active-value="true" :inactive-value="false" @change="couponfix(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" style="width: 10%;">
          <template slot-scope="scope">
            <p style="color: blue;cursor: pointer;" @click="showDetailDialog(scope.row)">查看详情</p>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers">
      </el-pagination>
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog :visible.sync="detailDialogVisible" title="优惠卷详情" width="500px">
      <el-form :model="detail" ref="editForm" label-width="200px">
        <div>
          <div class="detail-item" style="text-align: center;margin-top: -30px;">
            <h3>{{ detail.CouponName }}</h3>
          </div>
          <div style="margin-top: 15px;">
            <div class="detail-item">
              <p class="detail-label">优惠卷编号<span>{{ detail.CouponId }}</span></p>
            </div>
            <div class="detail-item">
              <p class="detail-label">优惠卷类型<span>{{ detail.CouponKind }}</span></p>
            </div>
            <div class="detail-item">
              <p class="detail-label">优惠卷金额<span>{{ detail.CouponMoney }}</span></p>
            </div>
            <div class="detail-item">
              <p class="detail-label">使用门槛 <span>{{ detail.CouponKey }}</span></p>
            </div>
            <div class="detail-item">
              <p class="detail-label">有效期 <span>
                  {{ formatTime(detail.CouponStarttime) }}</span>至<span>{{ formatTime(detail.CouponEndtime) }}</span>
              </p>
            </div>
            <div class="detail-item">
              <p class="detail-label">发放/领取/使用 <span>{{ detail.CouponTotal }}</span>/<span>{{ detail.CouponRec
              }}</span>/<span>{{ detail.CouponSit }}</span>
              </p>
            </div>
          </div>
        </div>
      </el-form>
      <span style="position: absolute;right: 20px;bottom: 20px;">
        <el-button @click="detailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="detailDialogVisible = false">确认</el-button>
      </span>
    </el-dialog>

    <!-- 活动弹窗 -->
    <el-dialog :visible.sync="addDialogVisible" title="新增优惠卷活动" width="700px">
      <el-form :model="newcoupon" ref="addForm" label-width="200px">
        <div style="margin-top: -20px;margin-bottom: 50px;">
          <div class="detail-item">
            <el-input v-model="newcoupon.CouponName" placeholder="请输入优惠卷名称"></el-input>
          </div>
          <div style="margin-top: 15px;">
            <div class="detail-item1">
              <p class="detail-label1">优惠卷类型</p>
              <el-select v-model="newcoupon.CouponKind" placeholder="请选择优惠卷类型">
                <el-option v-for="item in couponKindOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="detail-item1">
              <p class="detail-label1">优惠卷金额</p>
              <el-input v-model="newcoupon.CouponMoney" placeholder="请输入优惠卷金额"></el-input>
            </div>
            <div class="detail-item1">
              <p class="detail-label1">使用门槛</p>
              <el-input v-model="newcoupon.CouponKey" placeholder="请输入使用门槛"></el-input>
            </div>
            <div class="detail-item1">
              <p class="detail-label1">有效期</p>
              <el-date-picker style="margin-right: 10px;" v-model="newcoupon.CouponStarttime" type="date"
                placeholder="请选择活动开始时间" value-format="yyyy-MM-dd"></el-date-picker>
              至
              <el-date-picker style="margin-left: 10px;" v-model="newcoupon.CouponEndtime" type="date"
                placeholder="请选择活动结束时间" value-format="yyyy-MM-dd"></el-date-picker>
            </div>
            <div class="detail-item1">
              <p class="detail-label1">优惠卷总数量</p>
              <el-input v-model="newcoupon.CouponTotal" placeholder="请输入优惠卷的总数量"></el-input>
            </div>
          </div>
        </div>
      </el-form>
      <span style="position: absolute;right: 20px;bottom: 20px;">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="couponpost">确认</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认提示框 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="删除优惠卷" width="350px">
      <p>确定要删除优惠卷（{{ deleteUserNames.join(', ') }}）吗？此操作不可恢复</p>
      <span class="dialog-footer" style="margin-top: 20px;display: block;">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="coupondel">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui';
// import * as echarts from 'echarts';
import jq from "jquery";
export default {
  data() {
    return {
      coupon: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      detail: {},
      detailDialogVisible: false,
      addDialogVisible: false,
      remark: '',
      selectedCategory: '',
      selectedSeller: '',
      selectedBrowse: '',
      selectedEnquire: '',
      selectedCollect: '',
      selectedTransaction: '',
      batchStatus: '',
      batchRemark: '',
      selectedUsers: [],
      currentIndex: 0,
      // 的标签相关数据
      dynamicTags: [],
      newcouponTags: [],
      inputVisible: false,
      inputValue: '',
      newcoupon: {
        CouponName: '',
        CouponId: '',
        CouponKind: '',
        CouponMoney: '',
        CouponKey: '',
        CouponStarttime: '',
        CouponEndtime: '',
        CouponTotal: '',
        CouponRec: '0',
        CouponSit: '0',
        couponState: false,
      },
      deleteDialogVisible: false,
      deleteUserNames: [],
      couponKindOptions: [
        { value: '折扣价', label: '折扣价' },
        { value: '无门槛', label: '无门槛' },
        { value: '满减卷', label: '满减卷' },
      ]
    };
  },
  mounted() {
    document.querySelectorAll('.el-input input, .el-input select').forEach(input => {
      input.addEventListener('focus', () => {
        input.style.outline = 'none';
        input.style.borderColor = '#e2e2e2';
      });
    });
    this.totalUsers = this.coupon.length;
    this.usercoupon();
  },
  computed: {
    currentCoupons() {
      // 先根据搜索词过滤
      const filtered = this.coupon.filter(coupon =>
        coupon.CouponName.includes(this.searchQuery)
      );
      // 计算分页范围
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      // 返回当前页数据
      return filtered.slice(start, end);
    }
  },
  methods: {
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    //优惠卷查看
    usercoupon() {
      let _this = this;
      jq.ajax({
        type: "get",
        url: "http://127.0.0.1:3000/usercoupon",
        data: {
          value: this.add
        },
        success(res) {
          console.log('res', res);
          if (res.data == "") {
            return;
          } else {
            // 处理 CouponState 数据
            _this.coupon = res.data.map(item => {
              return {
                ...item,
                couponState: item.CouponState === '开启' ? true : false
              };
            });
            console.log('_this.coupon', _this.coupon);
          }
        }
      });
    },
    // 优惠卷删除方法
    coupondel() {
      let _this = this;
      // 遍历选中的用户，依次删除
      this.selectedUsers.forEach(coupon => {
        // 错误：this.coupon.CouponId（数组无此属性）
        // 正确：coupon.CouponId（当前选中的优惠券对象的属性）
        jq.ajax({
          type: 'delete',
          url: `http://127.0.0.1:3000/coupondel/${coupon.CouponId}`, // 修正此处
          success(res) {
            if (res.status === 200) {
              console.log(`删除优惠卷 ${coupon.CouponName} 成功`);
              // 从 coupon 数组中移除已删除的优惠券（根据 ID 过滤）
              _this.coupon = _this.coupon.filter(item => item.CouponId !== coupon.CouponId);
            } else {
              Message.error(`删除优惠卷 ${coupon.CouponName} 失败`);
              console.log(`删除优惠券失败，响应状态码:`, res.status);
            }
          },
          error(err) {
            console.error(`删除优惠卷 ${coupon.CouponName} 失败:`, err);
            Message.error(`删除优惠卷 ${coupon.CouponName} 失败`);
          }
        });
      });

      // 清空选中状态
      this.selectedUsers = [];
      this.deleteUserNames = [];
      this.deleteDialogVisible = false;
      this.totalUsers = this.coupon.length;
      this.currentPage = 1;
    },
    // 的更新优惠券状态方法
    couponfix(row) {
      const CouponState = row.couponState ? '开启' : '关闭';
      jq.ajax({
        type: 'put',
        url: `http://127.0.0.1:3000/couponfix`,
        data: {
          CouponId: row.CouponId,
          CouponState: CouponState
        },
        success(res) {
          if (res.status === 200) {
            Message.success(`更新优惠卷${row.CouponName} 成功`);
            console.log('更新优惠券成功');
          } else {
            Message.error('更新失败');
            console.log('更新优惠券失败，响应状态码:', res.status);
          }
        },
        error(err) {
          console.error('更新失败:', err);
          Message.error('更新失败');
          // 恢复原来的状态
          row.couponState = !row.couponState;
        }
      });
    },
    // 优惠卷方法
    couponpost() {
      console.log('进入 couponpost 方法');
      let _this = this;
      // 在发送请求之前生成新的 CouponId
      const maxNumber = this.coupon.length > 0 ? Math.max(...this.coupon.map(user => parseInt(user.CouponId.slice(2)), 10)) : 0;
      this.newcoupon.CouponId = `CO${(maxNumber + 1).toString().padStart(5, '0')}`;

      jq.ajax({
        type: 'post',
        url: 'http://127.0.0.1:3000/couponpost',
        data: {
          CouponName: _this.newcoupon.CouponName,
          CouponKind: _this.newcoupon.CouponKind,
          CouponMoney: _this.newcoupon.CouponMoney,
          CouponKey: _this.newcoupon.CouponKey,
          CouponStarttime: _this.newcoupon.CouponStarttime,
          CouponEndtime: _this.newcoupon.CouponEndtime,
          CouponTotal: _this.newcoupon.CouponTotal,
          CouponRec: '0',
          CouponSit: '0',
          CouponId: _this.newcoupon.CouponId,
          // 将布尔值转换为字符串
          CouponState: _this.newcoupon.couponState ? '开启' : '关闭'
        },
        success(res) {
          console.log('接口原始响应:', res);
          if (typeof res === 'object' && res !== null) {
            if (res.status === 200) {
              _this.addDialogVisible = false;
              _this.coupon.push(_this.newcoupon);
              _this.totalUsers = _this.coupon.length;
              Message.success(`添加优惠卷 ${_this.newcoupon.CouponName} 成功`);
              console.log('成功:', res.data);
              _this.usercoupon();
            } else {
              console.error('优惠卷失败，服务器返回非成功状态:', res);
            }
          }
        },
        error(err) {
          console.error('优惠卷失败，请求发生错误:', err);
          Message.error('优惠卷失败，请求发生错误');
        }
      });
    },
    searchUsers() {
      this.currentPage = 1; // 搜索时重置到第一页
      // 不需要手动过滤，计算属性会自动处理
      // 只需要更新总数量
      this.totalUsers = this.coupon.filter(coupon =>
        coupon.CouponName.includes(this.searchQuery)
      ).length;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      // 切换页大小后重置到第一页
      this.currentPage = 1;
      // 更新总数量
      this.totalUsers = this.coupon.filter(coupon =>
        coupon.CouponName.includes(this.searchQuery)
      ).length;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    getStateColor(couponState) {
      switch (couponState) {
        case '下架中':
          return '#F5F5F5';
        case '上架中':
          return '#E8F5E9';
        default:
          return 'transparent';
      }
    },
    getStateTextColor(couponState) {
      switch (couponState) {
        case '下架中':
          return '#333333';
        case '上架中':
          return '#006400';
        default:
          return 'transparent';
      }
    },
    showDetailDialog(row) {
      if (row) {
        this.detail = row;
        this.dynamicTags = row.CouponKind.split('，');
        this.detailDialogVisible = true;
      } else {
        console.error('传递的行数据row未定义');
      }
    },
    updateGoodsStatus(coupon, status, remark) {
      return new Promise((resolve) => {
        setTimeout(() => {
          coupon.couponState = status;
          if (status === '不通过') {
            coupon.processRecord = remark;
          }
          resolve();
        }, 1000);
      });
    },
    confirm() {
      console.log('点击了确认按钮，当前反馈状态：', this.detail.couponState);
      this.detailDialogVisible = false;
    },
    handleClose(tag) {
      const tags = this.addDialogVisible ? this.newcouponTags : this.dynamicTags;
      tags.splice(tags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        const inputElement = this.$refs.saveTagInput && this.$refs.saveTagInput.$refs.input;
        if (inputElement) {
          inputElement.focus();
        }
      });
    },
    handleInputConfirm() {
      if (this.inputValue) {
        const tags = this.addDialogVisible ? this.newcouponTags : this.dynamicTags;
        tags.push(this.inputValue);
        this.inputVisible = false;
        this.inputValue = '';
      }
    },
    showAddDialog() {
      this.newcoupon = {
        CouponName: '',
        CouponId: '',
        CouponKind: '',
        CouponMoney: '',
        CouponKey: '',
        CouponStarttime: '',
        CouponEndtime: '',
        CouponTotal: '',
        CouponRec: '0',
        CouponSit: '0',
        couponState: false
      };
      this.newcouponTags = [];
      this.addDialogVisible = true;
    },
    handleTableSelectionChange(selection) {
      this.selectedUsers = selection;
      this.deleteUserNames = selection.map(coupon => coupon.CouponName);
    },
    deleteSelected() {
      this.deleteDialogVisible = true;
    },
    couponaaa() {
      this.coupon = this.coupon.filter(coupon => {
        return !this.selectedUsers.some(selectedUser => selectedUser.CouponName === coupon.CouponName);
      });
      this.selectedUsers = [];
      this.deleteUserNames = [];
      this.deleteDialogVisible = false;
      Message.success('删除成功');
      this.totalUsers = this.coupon.length;
      this.currentPage = 1;
    },
  },
  created() {
    this.totalUsers = this.coupon.length;
  }
};
</script>


<style lang="less" scoped>
.coupon {
  padding: 70px 20px 20px 230px;
  background-color: #F9FAFB;
  width: 100%;

  .data-statistics {
    padding: 20px;
  }

  h2 {
    display: block;
    visibility: visible;
    margin-left: 10px;
  }

  .line-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    position: relative;
    margin: 20px 10px;
    padding: 20px 40px;
    width: 99%;

    .description-ellipsis {
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .box {
      width: 90%;

      select {
        margin-right: 10px;
      }

      .el-input {
        width: 400px;
        height: 40px;
        padding-left: 20px;
        color: #5d5a5a;
        font-size: 16px;
        margin: 10px 0 15px -12px;

        span {
          padding: 10px;
        }

        input {
          padding: 10px 34px;
          border-radius: 5px;
          border: 1px solid #e2e2e2;
          color: #5d5a5a;
        }
      }

      .el-button {
        margin-left: 10px;
        padding: 12px 25px;
        border-radius: 8px;


        img {
          position: relative;
          top: 2px;
          width: 15px;
          height: 15px;
        }
      }

      .remove {
        background-color: #f11f1f;
        color: white;
        position: absolute;
        top: 14px;
        right: 25px;
      }

      .process {
        background-color: #1f3ff1;
        color: white;
        position: absolute;
        top: 15px;
        right: 120px;
      }

      .border {
        border: 1px solid #e2e2e2;
        border-radius: 5px;
        background-color: transparent;
        font-size: 16px;
        padding-left: 20px;

        img {
          position: relative;
          top: 3px;
          right: 2px;
          width: 16px;
          height: 16px;
        }
      }

      .button {
        width: 400px;
        height: 40px;
        margin: 10px;
        border: transparent;
        background-color: #007BFF;
        color: white;
      }

      .color {
        background-color: #1f3ff1;
        color: white;
      }

    }

    h3 {
      display: block;
      padding: 30px 0 20px 20px;
    }
  }

  .pop {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

    p {
      font-size: 17px;
    }
  }

  .detail-row {
    display: flex;
    justify-content: space-around;
    margin-bottom: 10px;
    width: 100%;
  }

  .detail-main {
    width: 90%;
  }

  .detail-item {
    flex: 1;
    margin-right: 10px;
  }

  .detail-item1 {
    flex: 1;
    margin-top: 10px;
    // margin-right: 10px;
    // display: flex;
    // justify-content: space-between;
  }


  .detail-label {
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;

    span {
      color: #5d5a5a;
      margin: 0 10px;
    }
  }

  .detail-label1 {
    width: 100px;
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;

    span {
      color: #5d5a5a;
      margin: 0 10px;
    }
  }

  .close-button {
    background-color: #f4f4f4;
    color: #666;
    border: 1px solid #ccc;
  }

  .send-button {
    background-color: #409eff;
    color: white;
    border: none;
  }

  .confirm-button {
    background-color: #27c24c;
    color: white;
    border: none;
  }

  .stats-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: 20px 10px;
  }

  .stat-item {
    width: calc(50% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-item-1 {
    width: calc(25% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .stat-change {
    color: green;
  }

  .increase {
    color: green;
  }

  .decrease {
    color: red;
  }

  .stat-tip {
    color: rgb(255, 115, 0);
  }
}
</style>